#include "semantic_bridge.h"
#include "symbol_table.h"

static void process_ext_def(ParseNode node);
static void process_comp_st(ParseNode node, Type* return_type);
static void process_stmt(ParseNode stmt, Type* expected_return);
static Type* process_exp(ParseNode exp);
static Type* process_specifier(ParseNode node);
static Type* process_struct(ParseNode node);
static void process_def(ParseNode node, int is_struct_field);
static void process_dec_list(ParseNode dec_list, Type* spec_type, int is_struct_field);
static void process_dec(ParseNode dec, Type* spec_type, int is_struct_field); 
static void process_ext_dec_list(ParseNode node, Type* spec_type);
static void process_fun_dec(ParseNode func, Type* spec_type);
static Symbol* process_var_dec(ParseNode node, Type* spec_type);
static void process_var_list(ParseNode node, Type* func_type);
static Symbol* process_param_dec(ParseNode node);

/********************* 全局辅助函数 *********************/
static Type* create_basic_type(int basic_type) {
    Type* type = malloc(sizeof(Type));
    type->kind = BASIC;
    type->basic = basic_type;
    return type;
}

static Type* copy_type(Type* src) {
    if (!src) return NULL;
    Type* dest = malloc(sizeof(Type));
    memcpy(dest, src, sizeof(Type));

    // printf("%d, %d |\n",47 ,dest->basic);

    return dest;
}

// 添加变量到当前作用域
static void add_variable(Symbol* var) {
    if (check_symbol_conflict(var->name)) {
        fprintf(stderr, "Error type 3 at Line %d: Redefined variable '%s'\n",
               var->lineno, var->name);
        // free_symbol(var);
        return;
    }

    // 将变量信息添加到符号表（add_symbol 会复制必要数据）
    add_symbol(var->name, SYM_VARIABLE, var->type_info, var->lineno);
    
    // 释放当前 Symbol 对象（add_symbol 已深拷贝数据）
    // free_symbol(var);
}

static void add_struct_field(Symbol* var) {
    // 检查字段重定义
    if (check_symbol_conflict(var->name)) {
        fprintf(stderr, "Error type 15 at Line %d: Duplicate field '%s'\n",
               var->lineno, var->name);
        // free_symbol(var);
        return;
    }

    Symbol* exist = current_scope->symbols;
    while (exist) {
        if (strcmp(exist->name, var->name) == 0) {
            fprintf(stderr, "Error type 15 at Line %d: Duplicate field '%s'\n", 
                var->lineno, var->name);
            return;
        }
        exist = exist->next;
}

// 添加字段到当前结构体作用域
var->next = current_scope->symbols;
current_scope->symbols = var;  
}


// 类型兼容检查
static int type_compatible(Type* t1, Type* t2) {
    if (!t1 || !t2) return 0;

    // printf("%d, %d, %d |\n",45 ,t1->kind, t1->basic);
    // printf("%d, %d, %d |\n",46 ,t2->kind, t2->basic);
    
    // 处理隐式类型转换
    if (t1->kind == BASIC && t2->kind == BASIC) {
        return t1->basic == t2->basic;
    }
    
    if (t1->kind != t2->kind) return 0;
    
    switch (t1->kind) {
        case ARRAY:
            return (t1->array.size == t2->array.size) &&
                   type_compatible(t1->array.elem, t2->array.elem);
        case STRUCTURE:
            if (t1->structure.name && t2->structure.name && strcmp(t1->structure.name, t2->structure.name) == 0) {
                // 结构体比较字段结构
                Symbol *f1 = t1->structure.fields, *f2 = t2->structure.fields;
                while (f1 && f2) {
                    if (!type_compatible(f1->type_info, f2->type_info)) return 0;
                    if (strcmp(f1->name, f2->name) != 0) return 0;
                    f1 = f1->next;
                    f2 = f2->next;
                }
                return f1 == NULL && f2 == NULL;
            }

            return 0; // 匿名结构体不兼容
        case FUNCTION: {
            Symbol *p1 = t1->function.params, *p2 = t2->function.params;
            while (p1 && p2) {
                if (!type_compatible(p1->type_info, p2->type_info)) return 0;
                p1 = p1->next;
                p2 = p2->next;
            }
            return p1 == NULL && p2 == NULL; // 参数数量一致
        }
        default:
            return 1;
    }
}

// 检查ParseNode是否表示结构体定义（包含字段）
static int node_has_field_definition(ParseNode node) {
    return (node->child[2] != NULL); // 检查是否有LC DefList RC部分
}

// 获取结构体名称
static char* get_struct_name(ParseNode node) {
    ParseNode tag = node->child[1]; // Tag节点
    return strdup(tag->child[0]->ID);
}

/**************************************************************************************/

void semantic_check(ParseNode root) {
    // Program -> ExtDefList

    if (root == NULL)   return;

    enter_scope(); // 全局作用域
    ParseNode ext_def_list = root->child[0];

    // ExtDefList -> ExtDef ExtDefList

    // // printf("%d, %s |",0 ,root->name);
    // // printf("%d, %s |",1 ,ext_def_list->name);
    // printf("\n");

    while (ext_def_list) {
        process_ext_def(ext_def_list->child[0]);
        // printf("---------------------%d, %s |\n",1 ,ext_def_list->child[1]->name);

        // if (current_scope->symbols == NULL) printf("////////////////%d, %s |\n",76 ,"current_scope->symbols->name");
        // printf("////////////////%d, %s |\n",1 ,current_scope->symbols->name);
        // printf("////////////////%d, %s |\n",2 ,current_scope->symbols->type_info->structure.fields->name);

        ext_def_list = ext_def_list->child[1];
    }

    // exit_scope();
}

static void process_ext_def(ParseNode node) {
    // ExtDef -> Specifier SEMI

    if (node == NULL || strcmp(node->name, "ExtDef") != 0) {
        // fprintf(stderr, "Error: process_ext_def called with NULL node\n");
        return;
    }

    Type* spec_type = NULL;
    ParseNode spec = node->child[0];

    // printf("%d, %s |\n",0 ,spec->name);
    // printf("%d, %s |\n",1 ,spec->child[0]->name);

    // Specifier -> TYPE
    //	          | StructSpecifier
    if (strcmp(spec->child[0]->name, "TYPE") == 0) {
        spec_type = malloc(sizeof(Type));
        spec_type->kind = BASIC;
        spec_type->basic = (strcmp(spec->child[0]->ID, "int") ? 1 : 0);
    } else {
        // 处理结构体类型
        spec_type = process_struct(spec->child[0]);

        // 确保结构体定义有效
        if (!spec_type || !spec_type->structure.fields) {
            // fprintf(stderr, "Error type 17 at Line %d: Invalid struct definition\n", spec->lineno);
            return;
        }

        // 创建结构体类型符号
        Symbol* struct_sym = malloc(sizeof(Symbol));
        struct_sym->name = strdup(spec_type->structure.name);
        // spec_type->structure.name ? strdup(spec_type->structure.name) : generate_anonymous_struct_name();

        struct_sym->type = SYM_STRUCT;
        struct_sym->lineno = spec->lineno;
        struct_sym->type_info = malloc(sizeof(Type));
        
        // 深拷贝结构体类型
        struct_sym->type_info->kind = STRUCTURE;
        struct_sym->type_info->structure.name = struct_sym->name ? 
                                              strdup(struct_sym->name) : NULL;
        
        // 复制字段链表（保持原顺序）
        Symbol* src_field = spec_type->structure.fields;
        Symbol** dst_field = &struct_sym->type_info->structure.fields;
        while (src_field) {
            *dst_field = malloc(sizeof(Symbol));
            (*dst_field)->name = strdup(src_field->name);
            (*dst_field)->type_info = copy_type(src_field->type_info);
            (*dst_field)->type = SYM_VARIABLE;
            (*dst_field)->lineno = src_field->lineno;
            
            dst_field = &(*dst_field)->next;
            src_field = src_field->next;
        }
        *dst_field = NULL;

        add_symbol(struct_sym->name, SYM_STRUCT, struct_sym->type_info, spec->lineno);

        // printf("Added struct: %s\n", struct_sym->name);

        // printf("////////////////%d, %s, %d |\n",76 ,current_scope->symbols->name, current_scope->symbols->type);

        // printf("////////////////%d, %s, %d |\n",74 ,spec_type->structure.fields->name, spec_type->structure.fields->type_info->basic);
        // printf("////////////////%d, %s, %d |\n",75 ,spec_type->structure.fields->next->name, spec_type->structure.fields->next->type_info->basic);
    }

    // printf("%d, %d |\n",2 ,spec_type->basic);

    // ExtDef -> Specifier ExtDecList SEMI
    //         | Specifier FunDec CompSt
    ParseNode second = node->child[1];

    // printf("%d, %s |\n",3 ,second->name);

    if (strcmp(second->name, "ExtDecList") == 0) {
        process_ext_dec_list(second, spec_type);
    } else if (strcmp(second->name, "FunDec") == 0) {
        process_fun_dec(second, spec_type);

        // printf("%d, %s, %d |\n",5 ,node->child[2]->name, spec_type->basic);

        process_comp_st(node->child[2], spec_type);

        // printf("%d, %s |\n",58 ,current_scope->symbols->name);
        // // printf("%d, %s |\n",59 ,current_scope->symbols->next->name);

        // 退出参数作用域（如果有参数）
        if (second->child[2] && strcmp(second->child[2]->name, "VarList") == 0) {
            // exit_scope();
        }
    }

    // if (spec_type) free_type(spec_type);
}

static void process_fun_dec(ParseNode node, Type* return_type) {
    // FunDec -> ID LP VarList RP 
    //         | ID LP RP

    if (node == NULL || strcmp(node->name, "FunDec") != 0) {
        fprintf(stderr, "Error: process_fun_dec called with NULL node\n");
        return;
    }

    char* func_name = node->child[0]->ID;
    
    // 创建函数符号
    Symbol* func_sym = malloc(sizeof(Symbol));
    func_sym->name = strdup(func_name);
    func_sym->type = SYM_FUNCTION;
    func_sym->type_info = malloc(sizeof(Type));
    func_sym->type_info->kind = FUNCTION;
    func_sym->type_info->function.ret = copy_type(return_type);
    func_sym->type_info->function.params = NULL;

    // 检查函数是否重定义
    if (check_symbol_conflict(func_name)) {
        fprintf(stderr, "Error type 4 at Line %d: Redefined function '%s'\n", 
               node->lineno, func_name);
        free(func_sym->name);
        free_type(func_sym->type_info);
        free(func_sym);
        return;
    } else {
        add_symbol(func_name, SYM_FUNCTION, func_sym->type_info, node->lineno);

        // printf("%d, %s |\n",4 ,current_scope->symbols->name);
    }

    // 处理参数列表（如果有）
    if (node->child[2] && strcmp(node->child[2]->name, "VarList") == 0) {
        enter_scope(); // 进入参数作用域
        process_var_list(node->child[2], func_sym->type_info);
        // exit_scope();  // 不在这里退出作用域，在后序的语句块（Compst即大括号包裹的）分析结束后退出
    }

    // printf("%d, %s |\n",54 ,current_scope->symbols->name);
}

static void process_comp_st(ParseNode node, Type* return_type) {
    // CompSt -> LC DefList StmtList RC

    if (node == NULL || strcmp(node->name, "CompSt") != 0) {
        fprintf(stderr, "Error: process_comp_st called with NULL node\n");
        return;
    }

    // printf("%d, %s |\n",6 ,node->name);
    // printf("%d, %s |\n",7 ,node->child[0]->name);

    // printf("%d, %s |\n",52 ,current_scope->symbols->name);
    // // printf("%d, %s |\n",53 ,current_scope->parent->symbols->name);

    enter_scope();
    // 处理局部定义
    ParseNode def_list = node->child[1];

    // DefList -> Def DefList 
    while (def_list) {
        // printf("%d, %s |\n",8 ,def_list->name);

        process_def(def_list->child[0], return_type->kind == STRUCTURE);
        def_list = def_list->child[1];
    }

    // printf("%d, %d , %s|\n",68 ,current_scope->symbols->type_info->basic, current_scope->symbols->name);
    
    // 处理语句
    ParseNode stmt_list = node->child[2];
    while (stmt_list) {
        // printf("%d, %s |\n",24 ,stmt_list->name);

        process_stmt(stmt_list->child[0], return_type);
        stmt_list = stmt_list->child[1];
    }

    /* if (current_scope == NULL) printf("%d, %s |\n",50 ,"current_scope is NULL!!!");

    if (current_scope->symbols == NULL) printf("%d, %s |\n",51 ,"current_scope->symbols is NULL!!!");
    else printf("%d, %s |\n",51 ,current_scope->symbols->name);

    if (current_scope->parent == NULL) printf("%d, %s |\n",56 ,"current_scope->parent is NULL!!!");
    else printf("%d, %s |\n",56 ,current_scope->parent->symbols->name); */

    // printf("%d, %s |\n",56 ,current_scope->parent->symbols->next->name);

    // exit_scope();
}

static void process_def(ParseNode node, int is_struct_field) {
    // Def -> Specifier DecList SEMI

    if (node == NULL || strcmp(node->name, "Def") != 0) {
        // fprintf(stderr, "Error: process_def called with NULL node\n");
        return;
    }

    // printf("%d, %s |\n",9 ,node->name);
    // printf("%d, %s |\n",10 ,node->child[0]->name);

    // 1. 处理类型说明符（如 int、struct 等）
    Type* spec_type = process_specifier(node->child[0]);
    if (!spec_type) {
        // fprintf(stderr, "Error type 1 at Line %d: Invalid type specifier\n", node->lineno);
        return;
    }

    // printf("/////////////////////////%d, %s |\n",70 ,spec_type->structure.name);

    // 2. 处理声明列表（DecList）DecList -> Dec | Dec COMMA DecList 
    ParseNode dec_list = node->child[1];
    process_dec_list(dec_list, spec_type, is_struct_field);

    // 3. 清理类型资源
    // free_type(spec_type);
}

static void process_dec_list(ParseNode dec_list, Type* spec_type, int is_struct_field) {
    // DecList -> Dec 
    //          | Dec COMMA DecList

    if (dec_list == NULL || strcmp(dec_list->name, "DecList") != 0) {
        fprintf(stderr, "Error: process_dec_list called with NULL node\n");
        return;
    }

    // printf("%d, %s |\n",11 ,dec_list->name);
    // printf("%d, %s |\n",12 ,dec_list->child[0]->name);
    // printf("%d, %d |\n",13 ,spec_type->basic);

    while (dec_list && strcmp(dec_list->name, "DecList") == 0) {
        // 处理单个声明（Dec）
        ParseNode dec = dec_list->child[0];

        // printf("%d, %s |\n",14 ,dec->name);

        process_dec(dec, spec_type, is_struct_field);


        // 移动到下一个 Dec（如果有逗号分隔）
        if (dec_list->child[1] && strcmp(dec_list->child[1]->name, "COMMA") == 0) {
            dec_list = dec_list->child[2]; // 跳过 COMMA
        } else {
            break;
        }
    }
}

static void process_dec(ParseNode dec, Type* spec_type, int is_struct_field) {
    // Dec -> VarDec 
    //      | VarDec ASSIGNOP Exp
    if (dec == NULL || strcmp(dec->name, "Dec") != 0) {
        fprintf(stderr, "Error: process_dec called with NULL node\n");
        return;
    } 

    // printf("%d, %s |\n",15 ,dec->name);

    // 1. 处理变量声明（VarDec）
    ParseNode var_dec = dec->child[0];

    // printf("%d, %s |\n",16 ,var_dec->name);

    Symbol* var = process_var_dec(var_dec, spec_type);
    if (!var) return;

    // 2. 处理初始化表达式（如果有）
    ParseNode assign_exp = dec->child[1] ? dec->child[2] : NULL;

    /* if (assign_exp == NULL) printf("%d, %s |\n",20 ,"assign_exp->name is NULL");
    else printf("%d, %s |\n",20 ,assign_exp->name); */

    if (assign_exp) {
        // 检查结构体字段是否允许初始化
        if (is_struct_field) {
            fprintf(stderr, "Error type 15 at Line %d: Struct field cannot have initialization\n",
                   dec->lineno);
            // free_symbol(var);
            return;
        }

        // 检查初始化类型是否匹配
        Type* exp_type = process_exp(assign_exp);

        // printf("%d, %d |\n",21, spec_type->basic);
        // printf("%d, %d |\n",22, exp_type->basic);

        if (!type_compatible(spec_type, exp_type)) {
            fprintf(stderr, "Error type 5 at Line %d: Initialization type mismatch\n",
                   dec->lineno);
        }

        if (exp_type)  free_type(exp_type);
    }

    // 3. 根据上下文添加符号
    if (is_struct_field) {
        add_struct_field(var);  // 结构体字段添加到当前结构体
    } else {
        add_variable(var);      // 普通变量添加到当前作用域
    }

    // printf("---------------------%d, %d , %s |\n",67, current_scope->symbols->type_info->basic, var->name);
}

static Symbol* process_var_dec(ParseNode node, Type* spec_type) {
    // VarDec -> ID 
    //         | VarDec LB INT RB

    if (node == NULL || strcmp(node->name, "VarDec") != 0) {
        fprintf(stderr, "Error: process_var_dec called with NULL node\n");
        return NULL;
    }

    Symbol* var_sym = malloc(sizeof(Symbol));
    var_sym->name = NULL;
    var_sym->lineno = node->lineno;
    var_sym->type = SYM_VARIABLE;
    var_sym->type_info = copy_type(spec_type);

    ParseNode current = node;

    // printf("%d, %s |\n",17 ,current->name);
    // printf("%d, %d |\n",18 ,var_sym->type_info->basic);

    while (current->child) {
        // 处理数组声明（递归构建多维数组）
        if (strcmp(current->child[0]->name, "VarDec") == 0) {
            // printf("%d, %s |\n",19 ,current->child[1]->name);

            Type* array_type = malloc(sizeof(Type));
            array_type->kind = ARRAY;
            array_type->array.elem = var_sym->type_info;
            array_type->array.size = current->child[2]->INT;
            var_sym->type_info = array_type;
            current = current->child[0]; // 移动到内层VarDec
        } else {
            // 基础变量名
            var_sym->name = strdup(current->child[0]->ID);
            break;
        }
    }

    // printf("%1f, %s |\n",19.2 ,var_sym->name);

    return var_sym;
}

static Type* process_specifier(ParseNode node) {
    // Specifier -> TYPE
    //            | StructSpecifier

    if (node == NULL || strcmp(node->name, "Specifier") != 0) {
        fprintf(stderr, "Error: process_specifier called with NULL node\n");
        return NULL;
    }

    ParseNode t = node->child[0];

    // printf("+++++++++++++++++++++++++++++%d, %s |\n",80 ,t->name);

    if (strcmp(t->name, "TYPE") == 0) {
        if (strcmp(t->ID, "int") == 0) {
            return create_basic_type(INT_TYPE);
        } else {
            return create_basic_type(FLOAT_TYPE);
        }
    } else if (strcmp(t->name, "StructSpecifier") == 0) {
        if (node_has_field_definition(t)) { 
            // 处理结构体定义
            Type* struct_type = process_struct(t);

            printf("+++++++++++++++++++++++++++++%d, %d ,%s |\n",81 ,struct_type->kind, struct_type->structure.name);
            
            return struct_type;
        } else {
            // 处理结构体引用：查找已有定义
            char* struct_name = get_struct_name(t);
            Symbol* struct_def = find_symbol(struct_name);
            if (!struct_def || struct_def->type != SYM_STRUCT) {
                fprintf(stderr, "Error type 17 at Line %d: Undefined struct '%s'\n",
                       t->lineno, struct_name);
                return NULL;
            }

            // printf("@@@@@@@@@@@@@@@@@@@%d, %d ,%s |\n",81 ,struct_def->type_info->kind, struct_def->type_info->structure.fields->name);

            return copy_type(struct_def->type_info);
        }
    } else {
        fprintf(stderr, "Error type 1 at Line %d: Unknown specifier type '%s'\n",
               t->lineno, t->name);
        return NULL;
    }
}

static void process_stmt(ParseNode stmt, Type* expected_return) {
    // Stmt -> Exp SEMI
    //       | CompSt
    //       | RETURN Exp SEMI
    //       | IF LP Exp RP Stmt
    //       | IF LP Exp RP Stmt ELSE Stmt
    //       | WHILE LP Exp RP Stmt

    // printf("%d, %d |\n",29 ,expected_return->basic);

    if (stmt == NULL || strcmp(stmt->name, "Stmt") != 0) {
        // fprintf(stderr, "Error: process_stmt called with NULL node\n");
        return;
    }

    // Stmt -> RETURN Exp SEMI
    if (strcmp(stmt->child[0]->name, "RETURN") == 0) {
        Type* ret_type = process_exp(stmt->child[1]);
        if (ret_type && expected_return) {
            if (ret_type->kind != expected_return->kind ||
                (ret_type->kind == BASIC && ret_type->basic != expected_return->basic)) {
                fprintf(stderr, "Error type 8 at Line %d: Return type mismatch\n",
                       stmt->lineno);
            }
        }

        free_type(ret_type);
    }

    // Stmt -> CompSt
    else if (strcmp(stmt->child[0]->name, "CompSt") == 0) {
        process_comp_st(stmt->child[0],expected_return);
    }

    // Stmt -> Exp SEMI
    else if (strcmp(stmt->child[0]->name, "Exp") == 0) {
        Type* ret_type = process_exp(stmt->child[0]);

        if(ret_type == NULL) // printf("%d, %s |\n",25 ,"ret_type->basic is NULL");
        // printf("%d, %d |\n",26 ,expected_return->basic);

        if (ret_type && expected_return) {
            if (ret_type->kind != expected_return->kind ||
                (ret_type->kind == BASIC && ret_type->basic != expected_return->basic)) {
                fprintf(stderr, "Error type 8 at Line %d: Return type mismatch\n",
                       stmt->lineno);
            }
        }

        free_type(ret_type);
    }

    // Stmt -> WHILE LP Exp RP Stmt
    else if (strcmp(stmt->child[0]->name, "WHILE") == 0) {
        Type* cond_type = process_exp(stmt->child[2]);
        if (cond_type && cond_type->kind != BASIC) {
            fprintf(stderr, "Error type 7 at Line %d: Condition must be basic type\n",
                stmt->lineno);
        }
        process_stmt(stmt->child[4],expected_return);

        free_type(cond_type);
    }

    // Stmt -> IF LP Exp RP Stmt
    //       | IF LP Exp RP Stmt ELSE Stmt
    else if (strcmp(stmt->child[0]->name, "IF") == 0) {
        Type* cond_type = process_exp(stmt->child[2]);
        if (cond_type && cond_type->kind != BASIC) {
            fprintf(stderr, "Error type 7 at Line %d: Condition must be basic type\n",
                   stmt->lineno);
        }
        process_stmt(stmt->child[4], expected_return);
        if (stmt->child[5]) { // ELSE分支
            process_stmt(stmt->child[6], expected_return);
        }

        free_type(cond_type);
    }
}

static Type* process_exp(ParseNode exp) {
    // Exp -> Exp ASSIGNOP Exp .
    //      | Exp AND Exp .
    //      | Exp OR Exp .
    //      | Exp RELOP Exp .
    //      | Exp PLUS Exp .
    //      | Exp MINUS Exp .
    //      | Exp STAR Exp .
    //      | Exp DIV Exp .
    //      | LP Exp RP .
    //      | MINUS Exp .
    //      | NOT Exp .
    //      | ID LP Args RP .
    //      | ID LP RP .
    //      | Exp LB Exp RB .
    //      | Exp DOT ID .
    //      | ID .
    //      | INT .
    //      | FLOAT .
    if (exp == NULL || strcmp(exp->name, "Exp") != 0) {
        fprintf(stderr, "Error: process_exp called with NULL node\n");
        return NULL;
    }

    /* for (int i = 0; exp->child[i] != NULL; i++) {
        printf("    %d, %s |\n",i, exp->child[i]->name);
    } */

    // Exp -> Exp ASSIGNOP Exp
    if (exp->child[1] && strcmp(exp->child[1]->name, "ASSIGNOP") == 0) {
        // printf("%d, %s |\n",30 ,exp->child[0]->name);
        // printf("%d, %s |\n",31 ,exp->child[2]->name);

        // 检查左部是否为可赋值的表达式,赋值号左边能出现的只有ID、Exp LB Exp RB以及Exp DOT ID，
        int is_assignable = 0;
        ParseNode left_node = exp->child[0];

        Type* left = process_exp(exp->child[0]);

        // if (left) printf("%d, %d |\n",32 ,left->basic);

        Type* right = process_exp(exp->child[2]);

        // printf("%d, %s |\n",27 ,exp->child[0]->name);
        // printf("%d, %s |\n",28 ,exp->child[2]->name);
        
        // 左值检查
        if (strcmp(left_node->name, "Exp") == 0) {
            if (left_node->num == 1 && strcmp(left_node->child[0]->name, "ID") == 0) {
                // Exp → ID
                is_assignable = 1;
            } else if (left_node->num == 4 && strcmp(left_node->child[1]->name, "LB") == 0) {
                // Exp → Exp LB Exp RB（数组访问）
                is_assignable = 1;
            } else if (left_node->num == 3 && strcmp(left_node->child[1]->name, "DOT") == 0) {
                // Exp → Exp DOT ID（结构体成员访问）
                is_assignable = 1;
            }
        }
        
        if (!is_assignable) {
            fprintf(stderr, "Error type 6 at Line %d: Left side is not assignable\n", exp->lineno);
        }

        // if(left == NULL)     printf("%d, %s |\n",48 ,"Left is NULL!!!");
        // if(right == NULL)     printf("%d, %s |\n",49 ,"Right is NULL!!!");

        // 类型兼容检查
        if (left && right && !type_compatible(left, right)) {
            fprintf(stderr, "Error type 5 at Line %d: Assignment type mismatch\n",
                   exp->lineno);
        }

        Type* return_type = copy_type(left);

        if(return_type == NULL)    // printf("%d, %s |\n",48 ,"return_type is NULL!!!");

        free_type(left);
        free_type(right);

        return return_type;
    }

    // Exp -> Exp PLUS Exp
    //      | Exp MINUS Exp
    //      | Exp STAR Exp
    //      | Exp DIV Exp
    //      | Exp AND Exp
    //      | Exp OR Exp
    //      | Exp RELOP Exp
    if (exp->child[1] && (strcmp(exp->child[1]->name, "PLUS") == 0  ||
                          strcmp(exp->child[1]->name, "MINUS") == 0 ||
                          strcmp(exp->child[1]->name, "STAR") == 0  ||
                          strcmp(exp->child[1]->name, "DIV") == 0   ||
                          strcmp(exp->child[1]->name, "AND") == 0   ||
                          strcmp(exp->child[1]->name, "OR") == 0    ||
                          strcmp(exp->child[1]->name, "RELOP") == 0)) {
        // printf("%d, %s |\n",42 ,exp->child[0]->name);
        // printf("%d, %s |\n",43 ,exp->child[1]->name);
        // printf("%d, %s |\n",44 ,exp->child[2]->name);
        

        Type* t1 = process_exp(exp->child[0]);
        // printf("%d, %d |\n",40 ,t1->kind);

        Type* t2 = process_exp(exp->child[2]);
        // printf("%d, %d |\n",41 ,t2->kind);
        
        if (t1 && t2 && !type_compatible(t1, t2)) {
            fprintf(stderr, "Error type 7 at Line %d: Operand type mismatch\n",
                   exp->lineno);
        }

        Type* return_type = copy_type(t1);

        free_type(t1);
        free_type(t2);
        
        return return_type;
    }

    // Exp -> LP Exp RP
    if (strcmp(exp->child[0]->name, "LP") == 0) {
        Type* inner_type = process_exp(exp->child[1]);
        return inner_type; // 括号不改变类型，直接返回内部表达式类型
    }

    // Exp -> MINUS Exp
    if (strcmp(exp->child[0]->name, "MINUS") == 0) {
        Type* exp_type = process_exp(exp->child[1]);
        Type* result = NULL;

        if (!exp_type) {
            return NULL; // 子表达式已有错误
        }

        // 检查操作数是否为基本类型
        if (exp_type->kind != BASIC) {
            fprintf(stderr, "Error type 7 at Line %d: Operand of '-' must be basic type\n",
                   exp->lineno);
        } else {
            result = copy_type(exp_type); // 返回相同类型
        }

        free_type(exp_type);
        return result;
    }

    // Exp -> NOT Exp
    if (strcmp(exp->child[0]->name, "NOT") == 0) {
        Type* exp_type = process_exp(exp->child[1]);
        Type* result = NULL;

        if (!exp_type) {
            return NULL;
        }

        // 检查操作数是否为基本类型
        if (exp_type->kind != BASIC) {
            fprintf(stderr, "Error type 7 at Line %d: Operand of '!' must be basic type\n",
                   exp->lineno);
        } else {
            result = create_basic_type(INT_TYPE); // NOT操作结果总是int（0/1）
        }

        free_type(exp_type);
        return result;
    }

    // Exp -> ID LP Args RP
    //      | ID LP RP
    if (strcmp(exp->child[0]->name, "ID") == 0 && exp->child[1] &&
        strcmp(exp->child[1]->name, "LP") == 0) {

        // printf("%d, %s |\n",60 ,exp->child[0]->name);
        // printf("%d, %s |\n",61 ,exp->child[1]->name);

        Symbol* func = find_symbol(exp->child[0]->ID);
        if (!func || func->type != SYM_FUNCTION) {
            fprintf(stderr, "Error type 2 at Line %d: Undefined function '%s'\n",
                   exp->lineno, exp->child[0]->ID);
            return NULL;
        }

        // 参数检查
        Symbol* expected = func->type_info->function.params;
        ParseNode args = exp->child[2];
        while (expected && args) {
            Type* actual = process_exp(args->child[0]);

            // printf("%d, %d |\n",62 ,actual->kind);
            // printf("%d, %d |\n",63 ,expected->type_info->kind);

            if (!type_compatible(expected->type_info, actual)) {
                fprintf(stderr, "Error type 9 at Line %d: Argument type mismatch\n",
                       args->lineno);
            }
            expected = expected->next;
            args = args->child[2];
        }
        if (expected || args) {
            fprintf(stderr, "Error type 9 at Line %d: Argument count mismatch\n",
                   exp->lineno);
        }
        return copy_type(func->type_info->function.ret);
    }

    // Exp -> Exp LB Exp RB
    if (exp->child[1] && strcmp(exp->child[1]->name, "LB") == 0) {
        Type* t1 = process_exp(exp->child[0]);
        Type* t2 = process_exp(exp->child[2]);

        if (!t1 || t1->kind != ARRAY) {
            fprintf(stderr, "Error type 10 at Line %d: Not an array type\n", exp->lineno);
            return NULL;
        }
        if (!t2 || t2->kind != BASIC || t2->basic != INT_TYPE) {
            fprintf(stderr, "Error type 12 at Line %d: Array index must be integer\n", exp->lineno);
            return NULL;
        }

        Type* return_type = copy_type(t1->array.elem);

        free_type(t1);
        free_type(t2);
        
        return return_type;
    }

    // Exp -> Exp DOT ID
    if (exp->child[1] && strcmp(exp->child[1]->name, "DOT") == 0) {
        Type* t1 = process_exp(exp->child[0]);
        char* field_name = exp->child[2]->ID;
        
        if (!t1 || t1->kind != STRUCTURE) {
            fprintf(stderr, "Error type 13 at Line %d:  Illegal use of \".\"\n", exp->lineno);
            return NULL;
        }

        // printf("@@@@@@@@@@@@@@@@@@@@%d, %s |\n",87 ,t1->structure.fields->name);
        
        // 查找成员
        Symbol* struct_sym = find_symbol(t1->structure.name);
        if (!struct_sym) return NULL;
        
        Symbol* field = t1->structure.fields;
        while (field) {
            if (strcmp(field->name, field_name) == 0) {
                return copy_type(field->type_info);
            }
            field = field->next;
        }

        fprintf(stderr, "Error type 14 at Line %d: No such member '%s'\n", exp->lineno, field_name);
        return NULL;
    }

    // Exp -> ID
    if (strcmp(exp->child[0]->name, "ID") == 0) {
        // printf("------------------------%d, %s |\n",33 ,exp->child[0]->name);
        // printf("%d, %s |\n",34 ,exp->child[0]->ID);

        Symbol* sym = find_symbol(exp->child[0]->ID);

        // if (sym->type_info->structure.fields == NULL) printf("=====================================%d, %d|\n",86 ,sym->type_info->kind);

        if (!sym) {
            fprintf(stderr, "Error type 1 at Line %d: Undefined variable '%s'\n",
                   exp->lineno, exp->child[0]->ID);
            return NULL;
        }
        return copy_type(sym->type_info);
    }


    // Exp -> INT
    if (strcmp(exp->child[0]->name, "INT") == 0) {

        // printf("%d, %s |\n",23, exp->child[0]->name);

        return create_basic_type(INT_TYPE);
    }

    // Exp -> FLOAT
    if (strcmp(exp->child[0]->name, "FLOAT") == 0) {
        return create_basic_type(FLOAT_TYPE);
    }

    return NULL;
}

static void process_ext_dec_list(ParseNode node, Type* spec_type) {
    // ExtDecList -> VarDec 
    //             | VarDec COMMA ExtDecList

    if (node == NULL || strcmp(node->name, "ExtDecList") != 0) {
        fprintf(stderr, "Error: process_ext_dec_list called with NULL node\n");
        return;
    }

    ParseNode current = node;
    while (current) {
        // 处理单个变量声明
        Symbol* var = process_var_dec(current->child[0], spec_type);
        
        // 检查变量是否冲突（全局作用域）
        if (check_symbol_conflict(var->name)) {
            fprintf(stderr, "Error type 3 at Line %d: Redefined global variable '%s'\n", 
                   current->lineno, var->name);
            free(var);
        } else {
            add_symbol(var->name, SYM_VARIABLE, var->type_info, current->lineno);
        }
        
        // 处理逗号分隔的下一个声明
        if (current->child[1]) {
            current = current->child[2]; // 跳转到ExtDecList
        } else {
            break;
        }
    }
}


static void process_var_list(ParseNode node, Type* func_type) {
    // VarList -> ParamDec COMMA VarList 
    //          | ParamDec

    if (node == NULL || strcmp(node->name, "VarList") != 0) {
        fprintf(stderr, "Error: process_var_list called with NULL node\n");
        return;
    }

    ParseNode current = node;
    while (current) {
        // 处理单个参数
        Symbol* param = process_param_dec(current->child[0]);
        
        // 将参数添加到函数类型中
        param->next = func_type->function.params;
        func_type->function.params = param;

        // printf("-----------------------%d, %d |\n",65 ,func_type->function.params->type_info->kind);
        
        // 处理逗号分隔的下一个参数
        if (current->child[1]) {
            current = current->child[2]; // 跳转到VarList
        } else {
            break;
        }
    }
}

static Symbol* process_param_dec(ParseNode node) {
    // ParamDec -> Specifier VarDec

    if (node == NULL || strcmp(node->name, "ParamDec") != 0) {
        fprintf(stderr, "Error: process_param_dec called with NULL node\n");
        return NULL;
    }

    Type* param_type = process_specifier(node->child[0]);
    Symbol* param = process_var_dec(node->child[1], param_type);
    
    // 检查参数是否重复
    if (check_symbol_conflict(param->name)) {
        fprintf(stderr, "Error type 3 at Line %d: Duplicate parameter '%s'\n", 
               node->lineno, param->name);
        free(param);
        return NULL;
    }
    
    // 将参数添加到当前作用域（函数参数作用域）
    add_symbol(param->name, SYM_VARIABLE, param->type_info, node->lineno);

    // printf("----------------------%d, %d |\n",64 ,param->type_info->kind);

    return param;
}

static Type* process_struct(ParseNode node) {
    // StructSpecifier -> STRUCT OptTag LC DefList RC
    //                  | STRUCT Tag
    ParseNode opt_tag = node->child[1];
    ParseNode def_list = node->child[3];

    // printf("++++++++++++++++++++++++%d, %s |\n",90 ,opt_tag->name);


    Type* struct_type = malloc(sizeof(Type));
    struct_type->kind = STRUCTURE;
    struct_type->structure.name = opt_tag->child[0] ? strdup(opt_tag->child[0]->ID) : NULL;
    struct_type->structure.fields = NULL;

    // 进入结构体作用域
    enter_scope();

    // 处理字段定义
    while (def_list) {
        process_def(def_list->child[0], 1); // 标记为结构体字段
        def_list = def_list->child[1];
    }

    // 收集字段符号
    Symbol* field = current_scope->symbols;

    if (field == NULL) printf("++++++++++++++++++++++++%d, %s |\n",91 ,"current_scope->symbols");

    // printf("////////////////%d, %s |\n",70 ,current_scope->symbols->name);
    // printf("////////////////%d, %d |\n",70 ,current_scope->symbols->type_info->basic);
    // printf("////////////////%d, %s |\n",71 ,current_scope->symbols->next->name);
    // printf("////////////////%d, %d |\n",71 ,current_scope->symbols->next->type_info->basic);

    /// 收集字段符号（深拷贝）
    Symbol* src = current_scope->symbols;
    Symbol** dst = &struct_type->structure.fields;
    while (src) {
        *dst = malloc(sizeof(Symbol));
        (*dst)->name = strdup(src->name);
        (*dst)->type_info = copy_type(src->type_info);
        (*dst)->type = SYM_VARIABLE;
        (*dst)->lineno = src->lineno;
        (*dst)->next = NULL;
        
        dst = &(*dst)->next;
        src = src->next;
    }

    // 仅注册命名结构体
    if (struct_type->structure.name) {
        // 检查重复定义
        Symbol* exist = find_symbol(struct_type->structure.name);
        if (exist && exist->type == SYM_STRUCT) {
            fprintf(stderr, "Error type 16 at Line %d: Redefined struct '%s'\n",
                   node->lineno, struct_type->structure.name);
            // exit_scope();
            free_type(struct_type);
            return NULL;
        }

        // 注册到全局符号表
        Symbol* struct_sym = malloc(sizeof(Symbol));
        struct_sym->name = strdup(struct_type->structure.name);
        struct_sym->type = SYM_STRUCT;
        struct_sym->lineno = node->lineno;
        struct_sym->type_info = struct_type;

        Scope* global_scope = current_scope;
        while (global_scope->parent) global_scope = global_scope->parent;
        add_symbol(struct_sym->name, SYM_STRUCT, struct_type, node->lineno);
    }
    // exit_scope();

    // printf("////////////////%d, %s, %d |\n",72 ,struct_type->structure.fields->name, struct_type->structure.fields->type_info->basic);
    // printf("////////////////%d, %s, %d |\n",73 ,struct_type->structure.fields->next->name, struct_type->structure.fields->next->type_info->basic);

    return struct_type;
}